package com.heima.media.listener;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class PublishListener {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    @PostConstruct  // 在构造完成后执行该方法
    public void handleMessage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建一个队列
                RBlockingQueue<String> rQueue = redissonClient.getBlockingQueue("article-publish");
                // 为了解决建立连接的问题,每次启动时发送一条测试消息,在收到消息时过滤掉这个测试消息
                RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(rQueue);
                // 发送延迟消息
                delayedQueue.offer("init", 1, TimeUnit.SECONDS);
                while (true) {
                    String message = null;
                    try {
                        // 如果有消息进入redis的队列(list),直接取出消息,否则每隔1m查询一次
                        message = rQueue.poll(1, TimeUnit.MINUTES);
                        if (message != null && !message.equals("init")) {
                            System.out.println("接收到消息:" + message + " --- " + LocalDateTime.now());
                            // 发布文章
                            // 将消息转换成文章对象
                            WmNews wmNews = JSON.parseObject(message, WmNews.class);
                            auditService.audit(wmNews);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
